package com.qt.socket.bigwork;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * @Author zsf
 * @Date 2023/10/6 14:50
 * @Version 1.0
 */
public class ClientRoom {

    /**
     * 多人聊天室   大作业
     * @param args
     * @throws IOException
     */

    public static void main(String[] args) throws IOException {

        Socket socket = new Socket("127.0.0.1", 8888);
        Scanner sc = new Scanner(System.in);

        while (true) {
            System.out.println("服务器已经连接成功");
            System.out.println("==============欢迎来到qt聊天室================");
            System.out.println("1登录");
            System.out.println("2注册");
            System.out.println("请输入您的选择：");
            String selectMsg = sc.nextLine();

            if("1".equals(selectMsg)){
                login(socket);
            }else if("2".equals(selectMsg)){
                System.out.println("用户注册");
            }else {
                System.out.println("输入选项有误，请重新输入：");
            }
        }

    }

    private static void login(Socket socket) throws IOException {

        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String name = sc.nextLine();
        System.out.println("请输入密码：");
        String password = sc.nextLine();
        bw.write("login");
        bw.newLine();
        bw.flush();

        //第一次写入 要做什么操作
        //第二次写入 用户信息进行校验
        bw.write(name+"="+password);
        bw.newLine();
        bw.flush();


        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String checkStatus = br.readLine();
        System.out.println("checkStatus:"+checkStatus);
        //登录成功
        if("1".equals(checkStatus)){
            //开一个线程专门接收服务器发来的消息
            new Thread(new ClientRunnable(br)).start();
            //开启聊天模式
            talkAll(sc,bw);
        }else if("2".equals(checkStatus)){
            System.out.println("用户名不存在");
        }else if("3".equals(checkStatus)){
            System.out.println("密码错误");
        }




    }

    private static void talkAll(Scanner sc, BufferedWriter bw) throws IOException {
        //客户端发送消息
        while (true){
            System.out.println("请输入要发送的消息: ");
            String str = sc.nextLine();
            bw.write(str);
            bw.newLine();
            bw.flush();
        }
    }

}
